package com.beyondsoft.mcms.web;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
import com.beyondsoft.mcms.common.CommonUtils;
import com.beyondsoft.mcms.domain.Suggest;
import com.beyondsoft.mcms.service.MemberInfoService;

@RequestMapping("/suggests")
@Controller
@RooWebScaffold(path = "suggests", formBackingObject = Suggest.class)
public class SuggestController {

    @Autowired
    MemberInfoService memberInfoService;

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(Suggest suggest, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, suggest);
            return "suggests/create";
        }
        suggest.setSuggestDate(new Date());
        suggest.setProposer(CommonUtils.getCurrentMember());
        uiModel.asMap().clear();
        suggest.persist();
        return "redirect:/suggests";
    }

    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Suggest());
        return "suggests/create";
    }

    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("suggest", Suggest.findSuggest(id));
        uiModel.addAttribute("itemId", id);
        return "suggests/show";
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page == null) page = 1;
        if (page != null || size != null) {
            int sizeNo = size == null ? 5 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("suggests", Suggest.findSuggestEntries(firstResult, sizeNo));
            float nrOfPages = (float) Suggest.countSuggests() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
            uiModel.addAttribute("size", size);
            uiModel.addAttribute("page", page);
        }
        populateEditForm(uiModel, new Suggest());
        return "suggests/list";
    }

    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, Suggest.findSuggest(id));
        return "suggests/update";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Suggest suggest = Suggest.findSuggest(id);
        suggest.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/suggests";
    }

    void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("suggest_suggestdate_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
        uiModel.addAttribute("suggest_replydate_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }

    void populateEditForm(Model uiModel, Suggest suggest) {
        uiModel.addAttribute("suggest", suggest);
        addDateTimeFormatPatterns(uiModel);
    }

    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
        }
        return pathSegment;
    }

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@RequestParam("id") Long id, @RequestParam("replyContent") String replyContent, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel, HttpServletRequest httpServletRequest) {
        uiModel.asMap().clear();
        Suggest oldSuggest = Suggest.findSuggest(id);
        oldSuggest.setReply(CommonUtils.getCurrentUser());
        oldSuggest.setReplyContent(replyContent);
        oldSuggest.setReplyDate(new Date());
        oldSuggest.merge();
        return "redirect:/suggests?page=" + page + "&size=" + size;
    }
}
